package com.neusoft.bizcore.auth.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.auth.dto.AuthRoleCreateUpdateDTO;
import com.neusoft.bizcore.auth.dto.AuthRoleDTO;
import com.neusoft.bizcore.auth.model.AuthPermission;
import com.neusoft.bizcore.auth.model.AuthRole;
import com.neusoft.bizcore.auth.repository.AuthPermissionRepository;
import com.neusoft.bizcore.auth.repository.AuthRoleRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;

@Component
public class AuthRoleConverter extends AbstractConverter<AuthRole, AuthRoleDTO> {

    @Autowired
    private AuthRoleRepository authRoleRepository;
    @Autowired
    private AuthPermissionConverter authPermissionConverter;
    @Autowired
    private AuthPermissionRepository authPermissionRepository;
    @Autowired
    private AuthUserConverter authUserConverter;

    @Override
    public AuthRole toModel(final AuthRoleDTO dto) {
        AuthRole model;
        if (dto.isNew()) {
            model = new AuthRole();
        } else {
            model = this.authRoleRepository.getOne(dto.getId());
        }
        model.setName(dto.getName());
        model.setCode(dto.getCode());
        return model;
    }

    @Override
    public AuthRoleDTO toDTO(final AuthRole model, final boolean forListView) {
        final AuthRoleDTO dto = new AuthRoleDTO();
        dto.setId(model.getId());
        dto.setName(model.getName());
        dto.setCode(model.getCode());
        if (!forListView) {
            dto.getPermissions().addAll(this.authPermissionConverter.toListDTO(model.getPermissions()));
            dto.getUsers().addAll(this.authUserConverter.toListDTO(model.getUsers()));
        }
        return dto;
    }

    public AuthRole toModel(final AuthRoleCreateUpdateDTO dto) {
        AuthRole model;
        if (dto.isNew()) {
            model = new AuthRole();
        } else {
            model = this.authRoleRepository.getOne(dto.getId());
        }
        model.setName(dto.getName());
        model.setCode(dto.getCode());
        model.getPermissions().clear();
        for (final String code : dto.getPermissions()) {
            final AuthPermission permission = this.authPermissionRepository.findByCode(code);
            if (null != permission) {
                model.getPermissions().add(permission);
            }
        }
        return model;
    }

}
